package com.training.web.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.training.bean.Manager;
import com.training.jwt.JWTUtils;
import com.training.web.service.WebManagerService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebHomeController {

    @Autowired
    private WebManagerService webManagerService;

    @GetMapping("/home")
    public String homePage() {
        return "home";
    }
    
    @PostMapping("/home")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> home(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 解析token获取管理员信息
        DecodedJWT decodedJWT = JWTUtils.getToken(token);
        String phone = decodedJWT.getClaim("phone").asString();
        Manager manager = webManagerService.getManager(phone);
        Map<String, Object> result = new HashMap<>();
        result.put("manager", manager);
        return ResponseEntity.ok(result);
    }
}